
var MessagesView = View.extend(MessagesView = {
    init: function() {
        this.configureUI();
        this.configureSendInstant();
    },
    
    configureSendInstant: function() {
        var self = this;
        
        $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
            if ($(e.target).attr('href') == "#instant-history") {
                self.loadInstantHistory();
            }
        });

        $("#send_instant_btn").click(function( e ) {
            e.preventDefault();
            
            var contacts = [], 
                message =  $("#send_instant_form #send_instant_message").val();
                
            $(".pillbox li").each(function() {
                contacts.push({
                    name: $(this).text(),
                    number: $(this).attr('data-number')
                });
            });
            
            if( contacts.length == 0 ) {
                return false;
            }
            
            if( message.length == 0 ) {
                alert('Please enter a message that you would like to send');
                return;
            }

            confirm('You are about to send a direct SMS to the entered contacts. Do you want to continue?', function() {
                
                function enableFields(enable) {
                    if( enable ) {
                        $("#send_instant_form input").removeAttr('disabled');
                        $("#send_instant_form #send_instant_btn").addClass('btn-info').removeClass('btn-warning');
                    }
                    else {
                        $("#send_instant_form input").attr('disabled', true);
                        $("#send_instant_form #send_instant_btn").addClass('btn-warning').removeClass('btn-info');
                    }
                }
                
                enableFields(false);
                
                var url = $("#send_instant_form").attr('action');
                var params = {
                    contacts: contacts,
                    message: message
                };

                $.ajax({
                    url: url,
                    data: params,
                    type: 'post',
                    dataType: 'json',
                    success: function( response ) {
                        alert( response.message );
                        
                        if( response.status == 'success' ) {    
                            $('#sms_account_balance').text( response.account_balance );
                            $("#send_instant_form textarea").val('');
                            $("#send_instant_form .pillbox li").remove();
                        }
                        
                        enableFields(true);
                    },
                    error: function( xhr ) {
                        console.log( xhr.responseText );
                        enableFields(true);
                    }
                });
            });
        });
    },
    
    configureUI: function() {

        var addPill = function( $input, $id, $text, $number ) {
            var $pills = $input.closest('.pillbox'), $repeat = false, $repeatPill;
            if ( $text == "" ) {
                return;
            }

            $("li", $pills).text(function( i, v ) {
                if ( v == $text ) {
                    $repeatPill = $(this);
                    $repeat = true;
                }
            });

            if ( $repeat ) {
                $repeatPill.fadeOut().fadeIn();
                return;
            }

            var $item = $('<li class="label bg-info" data-id="' + $id + '" data-number="' + $number + '" title="' + $number + '">' + $text + '</li> ');
            $item.insertBefore($input);
            $pills.trigger('change', $item);

            setTimeout(function() {
                $input.val('');
            }, 50);
        };

        $(".pillbox input").autocomplete({
            source: $("#contacts-autocomplete-url").val(),
            minLength: 2,
            select: function( event, ui ) {
                if ( ui.item ) {
                    addPill($(this), ui.item.id, ui.item.value, ui.item.number);
                    $(this).val('');
                }
            },
            create: function() {
                $(this).data('ui-autocomplete')._renderItem = function( ul, item ) {
                    return $("<li>")
                            .append("<div class='name font-bold text-sm p-xs b-b bg-light'>" + item.label + "</div>")
                            .append("<div class='pu_content bg-white p-sm text-sm'>" + item.number + "</div>")
                            //.append('<a>' + item.label + '<br>' + item.value + '</a>')
                            .appendTo(ul);
                };

                $(this).data('ui-autocomplete')._resizeMenu = function() {
                    this.menu.element.outerWidth(300);
                };
            }
        });
    },
    
    loadInstantHistory: function() {
        if (this.loaded) {
            return;
        }

        var self = this;
        var url = $("#instant-history").data('href');

        $("#instant-history").html("Loading ...");

        $.ajax({
            url: url,
            type: 'post',
            success: function(response) {
                self.loaded = true;

                $("#instant-history").html(response);
            },
            error: function(xhr) {
                console.log(xhr.responseText);
            }
        });
    }
});

$(document).ready(function() {
    var messagesView = new MessagesView();
});
